class Admin::ProjectsController < AdminController
  
  before_filter :get_project, :except => [:index, :new, :create]
  before_filter :set_tags, :only => [:create, :update]
  
  def index
    @projects = Project.all
  end

  def new
    @project = Project.new
  end

  def create
    @project = Project.new(params[:project])
    set_tags
    respond_to do |wants|
      if @project.save
        flash[:notice] = 'Model was successfully created.'
        wants.js { render :partial => "show", :locals => {:project => @project} } 
        wants.html { redirect_to edit_admin_project_path(@project) } 
      else
        wants.js { render :partial => "show", :locals => {:project => @project} }
        wants.html { redirect_to admin_projects_path } 
      end
    end 
  end

  def edit
    @page_title = "Update #{@project.title}"
  end

  def update
    respond_to do |wants|
      if @project.update_attributes(params[:project])
        flash[:notice] = "Successfully updated project."
        wants.js { render :partial => "show", :locals => {:project => @project} } 
      else
        wants.js { render :partial => "show", :locals => {:project => @project} } 
      end
    end
  end
  
  def show_remote_form
    render :partial => "remote_form", :locals => {:project => @project}
  end
  
  def show
    render :partial => "show", :locals => {:project => @project}
  end

  def destroy
    @project.destroy
    flash[:notice] = "Successfully destroyed project."
    redirect_to admin_projects_url
  end
  
  protected
  
  def get_project
    @project = Project.find(params[:id])
  end
  
  def set_tags
    tags      = []
    new_tags  = params[:project][:tags].blank? ? [] : params[:project][:tags].split
    
    unless new_tags.blank?
      Tag.all.each do |t| 
        if new_tags.include?(t.stub_name)
          tags << t
          new_tags.delete(t.stub_name)
        end
      end
    
      new_tags.each do |t|
        tag = Tag.new(:name => t.gsub(/-/, " ").capitalize)
        tag.save
        tags << tag
      end
    
      @project.tags = tags
    end
  end
  
end




